package com.lonely.order.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lonely.common.utils.SecurityUtils;
import com.lonely.order.domain.dto.order.AddOrderLogDTO;
import com.lonely.order.domain.entity.SysOrder;
import com.lonely.order.domain.entity.SysOrderTag;
import com.lonely.order.domain.vo.order.OrderTagVO;
import com.lonely.order.mapper.SysOrderTagMapper;
import com.lonely.order.service.IOrderLogService;
import com.lonely.order.service.IOrderService;
import com.lonely.order.service.IOrderTagService;
import com.lonely.system.service.ISysTagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单标签服务实现类
 *
 * @author fzzf
 */
@Service
public class OrderTagServiceImpl extends ServiceImpl<SysOrderTagMapper, SysOrderTag> implements IOrderTagService {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private ISysTagService tagService;

    @Autowired
    private IOrderLogService orderLogService;

    /**
     * 查询指定订单id集合对应的标签列表
     *
     * @param orderIds 订单表主键id集合
     * @return
     */
    @Override
    public List<OrderTagVO> queryOrderTagsByOrderIds(List<Long> orderIds) {
        if (CollUtil.isEmpty(orderIds)) {
            return new ArrayList<>();
        }
        return super.getBaseMapper().queryOrderTagsByOrderIds(orderIds);
    }

    /**
     * 根据订单号查询订单标签
     *
     * @param produceOrderId
     * @return
     */
    @Override
    public List<String> getOrderTagIdsByProduceOrderId(Long produceOrderId) {
        SysOrder sysOrder = this.orderService.getOne(new LambdaQueryWrapper<SysOrder>().eq(SysOrder::getProduceOrderId, produceOrderId));
        Assert.notNull(sysOrder, "订单不存在");

        return super.list(new LambdaQueryWrapper<SysOrderTag>().eq(SysOrderTag::getOrderId, sysOrder.getId())).stream()
                .map(SysOrderTag::getTagId).distinct().map(StrUtil::toString).collect(Collectors.toList());
    }

    /**
     * 同步订单标签
     *
     * @param orderId
     * @param tagIds
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void synchronizeOrderTags(Long orderId, List<Long> tagIds) {

        // 获取该订单已存在的标签集合
        List<SysOrderTag> existsOrderTags = super.list(new LambdaQueryWrapper<SysOrderTag>()
                .eq(SysOrderTag::getOrderId, orderId)
        );
        List<Long> existsOrderTagIds = existsOrderTags.stream().map(SysOrderTag::getTagId).distinct().collect(Collectors.toList());

        // 获取待添加的tag集合
        List<Long> needAddTagIds = CollUtil.subtractToList(tagIds, existsOrderTagIds);

        // 获取待删除的tag集合
        List<Long> needDeleteTagIds = CollUtil.subtractToList(existsOrderTagIds, tagIds);

        if (CollUtil.isNotEmpty(needAddTagIds)) {
            List<SysOrderTag> needAddOrderTags = needAddTagIds.stream().map(x -> {
                SysOrderTag sysOrderTag = new SysOrderTag();
                sysOrderTag.setOrderId(orderId);
                sysOrderTag.setTagId(x);
                sysOrderTag.setCreateBy(SecurityUtils.getUserId());
                sysOrderTag.setUpdateBy(SecurityUtils.getUserId());
                return sysOrderTag;
            }).collect(Collectors.toList());
            super.saveBatch(needAddOrderTags);

            // 添加操作日志
            // 根据标签id获取对应的标签名称
            Map<Long, String> tagNameMap = this.tagService.getTagNameMapByTagIds(needAddTagIds);
            List<AddOrderLogDTO> orderLogs = needAddTagIds.stream().map(x -> {
                AddOrderLogDTO addOrderLogDTO = new AddOrderLogDTO();
                addOrderLogDTO.setOrderId(orderId);
                addOrderLogDTO.setTitle(String.format("添加标签：%s",tagNameMap.get(x)));
                return addOrderLogDTO;
            }).collect(Collectors.toList());
            this.orderLogService.batchAddOrderLog(orderLogs);
        }

        if (CollUtil.isNotEmpty(needDeleteTagIds)) {
            super.remove(new LambdaQueryWrapper<SysOrderTag>()
                    .eq(SysOrderTag::getOrderId, orderId)
                    .in(SysOrderTag::getTagId, needDeleteTagIds)
            );

            // 添加操作日志
            Map<Long, String> tagNameMap = this.tagService.getTagNameMapByTagIds(needDeleteTagIds);
            List<AddOrderLogDTO> orderLogs = needDeleteTagIds.stream().map(x -> {
                AddOrderLogDTO addOrderLogDTO = new AddOrderLogDTO();
                addOrderLogDTO.setOrderId(orderId);
                addOrderLogDTO.setTitle(String.format("删除标签：%s", tagNameMap.get(x)));
                return addOrderLogDTO;
            }).collect(Collectors.toList());
            this.orderLogService.batchAddOrderLog(orderLogs);
        }
    }
}
